<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item
            :to="{ name: 'MatchList' }"
            class="breadcrumb_active_item"
            >赛事名称管理</el-breadcrumb-item
          >
          <el-breadcrumb-item class="breadcrumb_active_item"
            ><span style="cursor: pointer">
              {{ matchtitle }}
            </span></el-breadcrumb-item
          >
          <el-breadcrumb-item>报名名单</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="audit_list_content">
        <el-row>
          <el-col :span="24">
            <el-tabs v-model="activeName" @tab-click="handleClick()">
              <el-tab-pane label="待审核列表" name="audit">
                <!-- 搜索框 -->
                <el-row style="margin-bottom: 10px">
                  <el-col :span="24">
                    <el-input
                      v-model="auditSearchKey"
                      placeholder="请输入关键词"
                      size="mini"
                      style="width: 200px; margin-left: 10px"
                    ></el-input>
                    <el-button
                      type="primary"
                      size="mini"
                      style="margin-left: 5px"
                      @click="searchFn(1)"
                      >搜索</el-button
                    >

                    <el-button
                      type="primary"
                      size="mini"
                      style="margin-left: 10px"
                      @click="auditBatch()"
                      >批量审核</el-button
                    >
                  </el-col>
                </el-row>
                <!-- 数据列表 -->
                <div
                  v-if="auditListData != undefined && auditListData.length > 0"
                >
                  <el-row>
                    <el-col :span="24">
                      <el-table
                        :data="auditListData"
                        border
                        size="mini"
                        :cell-style="cellStyleFn"
                        @selection-change="handleSelectionChange"
                        style="width: 100%"
                      >
                        <el-table-column type="selection" width="55">
                        </el-table-column>

                        <el-table-column
                          prop="department_name"
                          label="部门"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="pass_name"
                          label="证件种类"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="name"
                          label="姓名"
                          min-width="120"
                          align="center"
                        ></el-table-column>

                        <!-- <el-table-column
                          prop="phone"
                          label="手机号"
                          width="120"
                          align="center"
                        ></el-table-column> -->

                        <el-table-column
                          prop="company"
                          label="单位"
                          min-width="220"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="position"
                          label="岗位"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          label="权限区域"
                          width="300"
                          align="center"
                        >
                          <template slot-scope="scope">
                            <div class="tag_box">
                              <el-tag
                                v-for="(areaItem, index) in formatterAreaFn(
                                  scope.row.area_name
                                )"
                                :key="index"
                                style="margin: 0 5px 5px 0"
                                >{{ areaItem }}</el-tag
                              >
                            </div>
                          </template>
                        </el-table-column>

                        <el-table-column
                          prop="status_text"
                          label="审核状态"
                          width="120"
                          align="center"
                          :formatter="formatterStatusFn"
                        ></el-table-column>

                        <!-- <el-table-column
                          prop="created_at"
                          label="创建时间"
                          min-width="180"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="updated_at"
                          label="更新时间"
                          min-width="180"
                          align="center"
                        ></el-table-column> -->

                        <el-table-column
                          label="操作"
                          width="160"
                          align="center"
                        >
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="primary"
                              @click="auditDetailFn(scope.$index, scope.row)"
                            >
                              查看
                            </el-button>
                            <el-button
                              size="mini"
                              type="success"
                              v-if="scope.row.status == 1"
                              @click="auditBtnFn(scope.$index, scope.row)"
                            >
                              审核
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <div class="audit_list_pagination">
                        <el-pagination
                          @size-change="registrationListSizeChange"
                          @current-change="registrationListCurrentChange"
                          :current-page="auditCurrentPage"
                          :page-sizes="auditPageSizes"
                          :page-size="auditPageSize"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="auditTotal"
                        >
                        </el-pagination>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <el-row v-else>
                  <el-empty description="暂无数据"></el-empty>
                </el-row>
              </el-tab-pane>
              <el-tab-pane label="报名名单" name="registration">
                <!-- 搜索框 -->
                <el-row style="margin-bottom: 10px">
                  <el-col :span="24" style="display: flex; align-items: center">
                    <div>筛选：</div>
                    <el-select
                      v-model="isUsed"
                      placeholder="请选导出状态"
                      size="mini"
                      style="width: 150px; margin-left: 5px"
                      clearable
                      @change="isUsedSearchFn"
                    >
                      <el-option
                        v-for="item in isUsedstatusList"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                    <el-select
                      v-model="isModify"
                      placeholder="请选择更新状态"
                      size="mini"
                      style="width: 150px; margin-left: 5px"
                      clearable
                      @change="isModifySearchFn"
                    >
                      <el-option
                        v-for="item in isModifystatusList"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      >
                      </el-option>
                    </el-select>
                    <el-input
                      v-model="registrationSearchKey"
                      placeholder="请输入关键词"
                      size="mini"
                      style="width: 200px; margin-left: 10px"
                    ></el-input>
                    <el-button
                      type="primary"
                      size="mini"
                      style="margin-left: 5px"
                      @click="searchFn(2)"
                      >搜索</el-button
                    >
                    <el-button
                      type="primary"
                      size="mini"
                      style="margin-left: 10px"
                      :loading="downloadBtnLoading"
                      @click="exportFn()"
                      >{{ downloadBtnText }}</el-button
                    >
                  </el-col>
                </el-row>
                <!-- 数据列表 -->
                <div
                  v-if="
                    registrationListData != undefined &&
                    registrationListData.length > 0
                  "
                >
                  <el-row>
                    <el-col :span="24">
                      <el-table
                        :data="registrationListData"
                        border
                        size="mini"
                        :cell-style="cellStyleFn"
                        style="width: 100%"
                      >
                        <el-table-column
                          type="index"
                          label="序号"
                          width="50"
                          align="center"
                        >
                        </el-table-column>

                        <el-table-column
                          prop="department_name"
                          label="部门"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="pass_name"
                          label="证件种类"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="name"
                          label="姓名"
                          min-width="120"
                          align="center"
                        ></el-table-column>

                        <!-- <el-table-column
                          prop="phone"
                          label="手机号"
                          width="120"
                          align="center"
                        ></el-table-column> -->

                        <el-table-column
                          prop="company"
                          label="单位"
                          min-width="220"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          prop="position"
                          label="岗位"
                          min-width="160"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          label="权限区域"
                          width="300"
                          align="center"
                        >
                          <template slot-scope="scope">
                            <div class="tag_box">
                              <el-tag
                                v-for="(areaItem, index) in formatterAreaFn(
                                  scope.row.area_name
                                )"
                                :key="index"
                                style="margin: 0 5px 5px 0"
                                >{{ areaItem }}</el-tag
                              >
                            </div>
                          </template>
                        </el-table-column>

                        <el-table-column
                          prop="status_text"
                          label="审核状态"
                          width="120"
                          align="center"
                        ></el-table-column>
                        <!-- :formatter="formatterStatusFn" -->
                        <el-table-column
                          prop="is_used"
                          label="导出状态"
                          width="120"
                          align="center"
                          :formatter="formatterIsUsedStatusFn"
                        ></el-table-column>

                        <!-- <el-table-column
                          prop="created_at"
                          label="创建时间"
                          min-width="180"
                          align="center"
                        ></el-table-column> -->

                        <el-table-column
                          prop="updated_at"
                          label="审核时间"
                          min-width="180"
                          align="center"
                        ></el-table-column>

                        <el-table-column
                          label="操作"
                          width="160"
                          align="center"
                        >
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="primary"
                              @click="enrollDetailFn(scope.$index, scope.row)"
                            >
                              查看
                            </el-button>
                            <el-button
                              size="mini"
                              type="danger"
                              :disabled="userType == 1"
                              @click="enrollDeleteFn(scope.$index, scope.row)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <div class="audit_list_pagination">
                        <el-pagination
                          @size-change="registrationListSizeChange"
                          @current-change="registrationListCurrentChange"
                          :current-page="registrationCurrentPage"
                          :page-sizes="registrationPageSizes"
                          :page-size="registrationPageSize"
                          layout="total, sizes, prev, pager, next, jumper"
                          :total="registrationTotal"
                        >
                        </el-pagination>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <el-row v-else>
                  <el-empty description="暂无数据"></el-empty>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="400px"
    >
      <el-form
        ref="dialogDetailForm"
        :model="detailFormData"
        :rules="detailFormRules"
      >
        <el-form-item
          label="权限区域"
          prop="auditAreaList"
          v-if="dialogBtnKey == 1"
          :label-width="formLabelWidth"
        >
          <el-checkbox-group v-model="detailFormData.auditAreaList">
            <el-checkbox
              v-for="item in areaList"
              :key="item.id"
              :label="'' + item.id"
              >{{ item.area_name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="2"
            resize="none"
            style="width: 200px"
            placeholder="请输入内容"
            :autosize="{ minRows: 3, maxRows: 6 }"
            v-model="detailFormData.remark"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="approvedFn()"
          >通过</el-button
        >
        <el-button size="small" type="danger" @click="failedFn()"
          >不通过</el-button
        >
        <el-button size="small" @click="dialogclose()">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/audit/auditList.css" scoped></style>

<script>
import { saveAs } from "file-saver";
import JSZip from "jszip";

export default {
  name: "AuditList",
  components: {},
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      loadingKey: false,
      loadingText: "",
      matchtitle: "", // 赛事名称名称
      matchId: "", // 赛事名称id
      activeName: "audit", // tabs选中值
      registrationListData: [], // 数据列表--报名名单
      registrationCurrentPage: 1, // 当前页--报名名单
      registrationPageSizes: [10, 20, 50, 100], // 可选页容量--报名名单
      registrationPageSize: 10, // 当前页容量--报名名单
      registrationTotal: 0, // 总条数--报名名单
      registrationSearchKey: "", // 搜索关键词--报名名单
      statusList: [
        {
          key: 1,
          value: "审核中",
        },
        {
          key: 2,
          value: "审核完成",
        },
        {
          key: 3,
          value: "待重新提交审核",
        },
      ], // 审核状态字典
      isUsedstatusList: [
        {
          key: 1,
          value: "已导出",
        },
        {
          key: 2,
          value: "未导出",
        },
      ], // 导出状态字典
      isModifystatusList: [
        {
          key: 1,
          value: "已更新",
        },
        {
          key: 2,
          value: "未更新",
        },
      ], // 更新状态字典
      isUsed: "", // 导出状态
      isModify: "", // 更新状态
      auditListData: [], // 数据列表--审核列表
      auditCurrentPage: 1, // 当前页--审核列表
      auditPageSizes: [10, 20, 50, 100], // 可选页容量--审核列表
      auditPageSize: 10, // 当前页容量--审核列表
      auditTotal: 0, // 总条数--审核列表
      auditSearchKey: "", // 搜索关键词--审核列表
      dialogTitle: "", // 弹窗标题
      dialogVisible: false, // 弹窗显示
      dialogBtnKey: 1, // 审核弹窗控制 1. 单条审核; 2. 批量审核
      detailFormData: {
        id: "",
        auditAreaList: [], // 权限区域
        remark: "", // 备注
      }, // 部门弹窗数据
      detailFormRules: {
        // auditAreaList: [
        //   { required: true, message: "请勾选权限区域", trigger: "change" },
        // ],
      },
      formLabelWidth: "100px",
      areaList: [], // 权限区域列表
      tableSelect: [], // 审核列表勾选
      downloadBtnLoading: false,
      downloadBtnText: "导出名单",
      downloadMax: 0,
      downloadNow: 0,
    };
  },
  created: function () {
    let query = this.$route.query;
    if (query.id != undefined && query.id != "") {
      this.matchId = query.id;
    }

    this.getAuditListDataFn();
    this.getAreaListDataFn();
  },
  methods: {
    // 导出状态筛选
    isUsedSearchFn: function (val) {
      this.isUsed = val;
      this.registrationCurrentPage = 1;
      this.getRegistrationListDataFn();
    },
    // 通过状态筛选
    isModifySearchFn: function (val) {
      this.isModify = val;
      this.registrationCurrentPage = 1;
      this.getRegistrationListDataFn();
    },
    // 搜索按钮
    searchFn: function (key) {
      if (key == 1) {
        this.auditCurrentPage = 1;
        this.getAuditListDataFn();
      } else {
        this.registrationCurrentPage = 1;
        this.getRegistrationListDataFn();
      }
    },
    // 获取权限区域列表数据
    getAreaListDataFn: function () {
      let that = this;
      let url = "/admin/area/index";
      let data = {
        event_id: this.matchId,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.areaList = response.list;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 获取报名名单列表数据
    getRegistrationListDataFn: function () {
      let that = this;
      let url = "/admin/apply/index";
      let data = {
        event_id: this.matchId,
        page: this.registrationCurrentPage,
        perPage: this.registrationPageSize,
        keywords: this.registrationSearchKey,
        is_used: this.isUsed,
        is_modify: this.isModify,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.registrationListData = response.list;
            that.registrationTotal = response.total_count;
            that.matchtitle = response.event.title;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 报名名单页容量改变
    registrationListSizeChange: function (val) {
      this.registrationCurrentPage = 1;
      this.registrationPageSize = val;
      this.getRegistrationListDataFn();
    },
    // 报名名单当前页改变
    registrationListCurrentChange: function (val) {
      this.registrationCurrentPage = val;
      this.getRegistrationListDataFn();
    },
    // 获取审核列表数据
    getAuditListDataFn: function () {
      let that = this;
      let url = "/admin/apply/auditList";
      let data = {
        event_id: this.matchId,
        page: this.auditCurrentPage,
        perPage: this.auditPageSize,
        keywords: this.auditSearchKey,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.auditListData = response.list;
            that.auditTotal = response.total_count;
            that.matchtitle = response.event.title;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 审核列表页容量改变
    auditListSizeChange: function (val) {
      this.auditCurrentPage = 1;
      this.auditPageSize = val;
      this.getAuditListDataFn();
    },
    // 审核列表当前页改变
    auditListCurrentChange: function (val) {
      this.auditCurrentPage = val;
      this.getAuditListDataFn();
    },
    // 列表勾选
    handleSelectionChange: function (val) {
      this.tableSelect = val;
    },
    // tabs选中
    handleClick: function (v) {
      console.log(this.activeName);
      if (this.activeName == "registration") {
        this.registrationCurrentPage = 1;
        this.getRegistrationListDataFn();
      } else {
        this.auditCurrentPage = 1;
        this.getAuditListDataFn();
      }
    },
    // 审核状态格式化
    formatterStatusFn: function (row) {
      let status = row.status;
      let text = "";
      this.statusList.forEach(function (item) {
        if (item.key == status) {
          text = item.value;
        }
      });
      return text;
    },
    // 导出状态格式化
    formatterIsUsedStatusFn: function (row) {
      let is_used = row.is_used;
      let text = "";
      this.isUsedstatusList.forEach(function (item) {
        if (item.key == is_used) {
          text = item.value;
        }
      });
      return text;
    },

    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 7) {
        if (row.status != 2) {
          style = "color: #F6705E";
        } else {
          style = "color: #8ECF5F";
        }
      }
      if (columnIndex == 8) {
        if (row.is_used != 1) {
          style = "color: #F6705E";
        } else {
          style = "color: #8ECF5F";
        }
      }
      return style;
    },

    // 审核按钮
    auditBtnFn: function (index, row) {
      let that = this;
      this.dialogTitle = "审核";
      this.dialogBtnKey = 1;
      this.detailFormData = {
        id: row.id,
        auditAreaList: [],
        remark: "",
      };
      if (
        row.area_ids != "" &&
        row.area_ids != null &&
        row.area_ids != undefined
      ) {
        this.detailFormData.auditAreaList = row.area_ids.split(",");
      }

      this.$nextTick(function () {
        that.dialogVisible = true;
      });
    },

    // 审核通过
    approvedFn: function () {
      let that = this;
      let url = "";
      let data = {
        remark: that.detailFormData.remark,
        operate: 1,
      };
      if (this.dialogBtnKey == 1) {
        url = "/admin/apply/audit";
        data.area_ids = that.detailFormData.auditAreaList.join(",");
        data.apply_id = that.detailFormData.id;
      } else {
        url = "/admin/apply/auditBatch";
        data.apply_ids = that.detailFormData.id;
      }

      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          this.$confirm("确认通过该流程?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }).then(() => {
            that.loadingText = "处理中...";
            that.loadingKey = true;
            that.axios
              .post(url, data)
              .then((response) => {
                that.loadingKey = false;
                if (response.code == 0) {
                  that.$message.success("操作成功");
                  that.dialogclose();
                  that.getAuditListDataFn();
                } else {
                  that.$message.error(response.msg);
                }
              })
              .catch(function (error) {
                that.loadingKey = false;
                console.log(error);
              });
          });
        }
      });
    },

    // 审核不通过
    failedFn: function () {
      let that = this;
      let url = "";
      let data = {
        remark: that.detailFormData.remark,
        operate: 2,
      };
      if (this.dialogBtnKey == 1) {
        url = "/admin/apply/audit";
        data.area_ids = that.detailFormData.auditAreaList.join(",");
        data.apply_id = that.detailFormData.id;
      } else {
        url = "/admin/apply/auditBatch";
        data.apply_ids = that.detailFormData.id;
      }

      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          this.$confirm("确认不通过该流程?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }).then(() => {
            that.loadingText = "处理中...";
            that.loadingKey = true;
            that.axios
              .post(url, data)
              .then((response) => {
                that.loadingKey = false;
                if (response.code == 0) {
                  that.$message.success("操作成功");
                  that.dialogclose();
                  that.getAuditListDataFn();
                } else {
                  that.$message.error(response.msg);
                }
              })
              .catch(function (error) {
                that.loadingKey = false;
                console.log(error);
              });
          });
        }
      });
    },

    // 审核列表--查看
    auditDetailFn: function (index, row) {
      const routeUrl = this.$router.resolve({
        name: "AuditDetail",
      });
      window.open(
        routeUrl.href + "?id=" + row.id + "&key=1&header=3",
        "_blank"
      );
    },

    // 报名列表--查看
    enrollDetailFn: function (index, row) {
      const routeUrl = this.$router.resolve({
        name: "AuditDetail",
      });
      window.open(
        routeUrl.href + "?id=" + row.id + "&key=2&header=3",
        "_blank"
      );
    },
    // 报名列表--删除
    enrollDeleteFn: function (index, row) {
      let that = this;
      let url = "/admin/apply/destroy";
      let data = {
        id: row.id,
      };

      this.$confirm("是否导删除该报名?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              let next = that.registrationCurrentPage - 1;
              if (that.registrationListData.length == 1) {
                that.registrationCurrentPage = next >= 1 ? next : 1;
              }
              that.getRegistrationListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },

    // 关闭弹窗
    dialogclose: function () {
      this.dialogVisible = false;
    },
    // 批量审核
    auditBatch: function () {
      let that = this;
      this.dialogTitle = "审核";
      this.dialogBtnKey = 2;
      let list = [];
      if (this.tableSelect.length == 0) {
        that.$message.error("请先选择审核记录");
        return false;
      }
      this.tableSelect.forEach((item) => {
        list.push(item.id);
      });

      this.detailFormData = {
        id: list,
        auditAreaList: [],
        remark: "",
      };

      this.$nextTick(function () {
        that.dialogVisible = true;
      });
    },
    // 导出名单
    exportFn: function () {
      let that = this;
      let url = "/excel/exportApply";
      let data = {
        event_id: that.matchId,
        is_used: that.isUsed,
        is_modify: that.isModify,
      };

      this.$confirm("是否导出名单数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        that.downloadBtnLoading = true;
        that.downloadBtnText = "下载中...";
        that.axios
          .post(url, data, { responseType: "blob" })
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 1) {
              that.downloadBtnLoading = false;
              that.downloadBtnText = "导出名单";
              that.$message.error(response.msg);
            } else {
              let blob = new Blob([response], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
              });
              // const link = document.createElement("a");
              // 这里是将链接地址url转成blob地址，
              // link.href = URL.createObjectURL(blob);
              // // 下载文件的名称及文件类型后缀
              // link.download = "报名名单.xlsx";
              // document.body.appendChild(link);
              // link.click();
              // // 在资源下载完成后 清除 占用的缓存资源
              // window.URL.revokeObjectURL(link.href);
              // document.body.removeChild(link);
              that
                .getImgUrlListFn()
                .then((res) => {
                  if (res) {
                    that.downloadZip(res, blob);
                  }
                })
                .catch((err) => {
                  that.$message.error("网络繁忙,请稍后重试");
                });
            }
          })
          .catch(function (error) {
            that.downloadBtnLoading = false;
            that.downloadBtnText = "导出名单";
            console.log(error);
          });
      });
    },
    // 获取下载照片链接
    getImgUrlListFn: function () {
      let that = this;
      let data = {};
      data = {
        event_id: that.matchId,
        is_used: that.isUsed,
        is_modify: that.isModify,
      };
      let url = "/admin/apply/exportApplyPhoto";
      return new Promise(function (resolve, reject) {
        that.axios
          .post(url, data)
          .then((response) => {
            if (response.code == 0) {
              let list = response.list;
              resolve(list);
            } else {
              that.$message.error(response.msg);
              resolve(false);
            }
          })
          .catch(function (error) {
            reject(error);
          });
      });
    },
    // 下载
    downloadFileFn: function (url) {
      return new Promise((resolve, reject) => {
        fetch(url, {
          mode: "cors",
        })
          .then((res) => res.blob())
          .then((blob) => {
            resolve(blob);
          })
          .catch((error) => {
            that.$message.error("网络错误");
            reject(error.toString());
          });
      });
    },
    // 下载打包
    downloadZip: function (list, excel) {
      let that = this;
      let upList = [];
      let imgList = list;
      const zip = new JSZip();
      const promises = [];

      zip.file("报名名单.xlsx", excel);

      imgList.forEach(function (item) {
        if (
          item.local_photo != null &&
          item.local_photo != "" &&
          item.local_photo != undefined
        ) {
          const typeIndex = item.local_photo.indexOf(".");
          let fileType = item.local_photo.slice(
            typeIndex,
            item.local_photo.length
          );
          // let name = item.name + "(" + item.id + ")" + fileType;
          let name = item.name + fileType;
          console.log(name);
          upList.push(item);
          const promise = that
            .downloadFileFn(that.baseAPIUrl + "/" + item.local_photo)
            .then((data) => {
              let cil = 0;
              that.downloadNow++;
              cil = Math.floor((that.downloadNow / that.downloadMax) * 100);
              that.downloadBtnText = "下载中 " + cil + "%";
              zip.file(name, data);
            })
            .catch((error) => {
              that.$message.error("网络错误");
            });
          promises.push(promise);
        }
      });
      that.downloadMax = upList.length + 1;
      that.downloadNow = 0;
      Promise.all(promises).then(() => {
        zip
          .generateAsync({
            type: "blob",
          })
          .then((content) => {
            saveAs(content, "报名名单.zip");
            this.downloadBtnLoading = false;
            this.downloadBtnText = "导出名单";
          })
          .catch((error) => {
            that.$message.error("网络错误");
          });
      });
    },
    // 权限区域格式化
    formatterAreaFn: function (val) {
      let list = val.split(",");
      return list;
    },
  },
};
</script>
<style scoped>
</style>
